<template>
    <div class="integratedQuery">
        <base-dialog :dialogObj="editViewsDialog" class="base-dialog edit-views">
            <template v-slot:content>
                <div v-if="isAdmin" class="edit-views-setting">
                    <el-checkbox v-model="settingType"> 存为系统配置 </el-checkbox>
                </div>
                <div class="edit-views-box">
                    <div v-for="(item, index) in deepModuleList" :key="index" class="box-item mgb-12">
                        <p class="mgb-6">
                            {{ $t(item.label) }}
                        </p>
                        <base-table
                            :tableData="item.list"
                            :colunmData="tableHeaderConfig[item.value]"
                            :tableConfig="{
                                isMultiSelect: false,
                                isIndex: true,
                                maxHeight: '200px'
                            }"
                        >
                            <template v-slot="{ scope }">
                                <el-button id="btn_t_gray" type="text" size="mini" @click.stop.prevent="deleteItem(scope, item.list)">
                                    {{ $t('layout.btns.delete') }}
                                </el-button>
                            </template>
                        </base-table>
                        <div class="add-box f12">
                            <p class="inline-block" @click="addModuleId(item, index)">
                                +{{
                                    $t(
                                        `commonWord.${
                                            item.value === 'relationModuleList'
                                                ? 'addModule'
                                                : item.value === 'relationReportList'
                                                ? 'addReport'
                                                : 'addLink'
                                        }`
                                    )
                                }}
                            </p>
                        </div>
                    </div>
                </div>
            </template>
            <template v-slot:footerBtn>
                <div class="edit-views-btn">
                    <el-button @click="cancel">
                        {{ $t('layout.btns.cancel') }}
                    </el-button>
                    <el-button @click="reset"> 恢复默认 </el-button>
                    <el-button type="primary" @click="confirm">
                        {{ $t('layout.btns.sure') }}
                    </el-button>
                </div>
            </template>
        </base-dialog>
        <base-dialog :dialogObj="addModuleAndReport" class="base-dialog edit-views" @confirm="moduleAndReportConfim">
            <template v-slot:content>
                <base-tree
                    ref="baseTree"
                    :optionDatas="addKey === 'relationModuleList' ? bussinerRouter : reportRouter"
                    :treeConfig="{
                        isFilter: true,
                        showCheckbox: true
                    }"
                />
            </template>
        </base-dialog>
        <base-dialog :dialogObj="linkModuleDialogObj" class="base-dialog edit-views" @confirm="linkModuleIdConfirm">
            <template v-slot:content>
                <!-- <base-input></base-input> -->
                <formList ref="formlist" :formList="linkFormlist" :formData="linkFormData" />
            </template>
        </base-dialog>
    </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Prop, Watch } from 'vue-property-decorator';
import { Dictionary, DialogObj, TableHeaderConfig, TreeObject, FormListConfig } from '@/typings';
import Component from 'vue-class-component';
import { getRouters } from '@/api/user';
import { nest, deepCopy } from '@/utils';
import { Tools } from '@/utils/tools';
import commonApi from '@/api/common-api';
import baseTree from '@/components/base-tree/index.vue';
// import commonApi from '@/api/common-api'
// const MODULE_TYPE = new Map([
//   ['1', ['moduleList', 'layout.btns.relatedModules']],
//   ['2', ['reportList', 'layout.btns.relatedReports']],
//   ['3', ['webList', 'layout.btns.relatedWeb']]

// ])
// {
//   1: 'moduleList',
//   2: 'reportList',
//   3: 'webList',
//   4: 'externaList'
// }
@Component({
    name: 'edit-views',
    components: {
        baseDialog: () => import('@/components/base-dialog/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue'),
        baseInput: () => import('@/components/base-input/index.vue'),
        formList: () => import('@/components/formlist/index.vue'),
        baseTree
    }
})
export default class editViews extends Vue {
    @Prop({ required: true }) moduleList: any[];
    @Prop({ required: true }) editViewsDialog: DialogObj;
    isAdmin() {
        return this.$store.state.user.userNo === 'admin';
    }
    @Watch('moduleList', { immediate: true })
    onModuleListChange(val) {
        this.deepModuleList = deepCopy(val);
    }
    linkFormData: Dictionary<any> = {};
    addModuleAndReport: DialogObj = {
        isShowDialog: false,
        title: '添加模块/报表',
        width: '30%'
    };
    linkModuleDialogObj: DialogObj = {
        setShow: true,
        isShowDialog: false,
        title: '添加外链模块',
        width: '30%'
    };
    deepModuleList: any[] = [];
    menuTree: TreeObject[] = [];
    reportRouter: TreeObject[] = [];
    bussinerRouter: TreeObject[] = [];
    current: Dictionary = {};
    addKey: string = '';
    tableHeaderConfig: Dictionary<TableHeaderConfig[]> = {
        relationModuleList: [
            {
                label: '模块',
                value: 'label'
            }
        ],
        relationReportList: [
            {
                label: '报表',
                value: 'label'
            }
        ],
        externalLinkList: [
            {
                label: '相关外链模块',
                value: 'label'
            }
        ]
    };
    linkFormlist: FormListConfig[] = [
        {
            label: '模块名称',
            value: 'label',
            lang: 'menuConfig.moduleTableHeader.name',
            type: 'input',
            setLength: 24,
            rules: [
                {
                    required: true,
                    message: '请输入模块名称',
                    trigger: 'blur'
                }
            ]
        },
        {
            label: '模块类型',
            value: 'type',
            lang: 'commonWord.type',
            type: 'radio',
            setLength: 24,
            rules: [
                {
                    required: true,
                    message: '请输入模块类型',
                    trigger: 'change'
                }
            ],
            options: [
                {
                    label: '嵌入式',
                    value: 3
                },
                {
                    label: '弹出式',
                    value: 4
                }
            ]
        },
        {
            label: 'URL',
            value: 'moduleId',
            lang: 'commonWord.url',
            type: 'input',
            setLength: 24,
            rules: [
                {
                    required: true,
                    message: '请输入URL',
                    trigger: 'blur'
                }
            ]
        }
    ];
    isShowDrawer: boolean = false;
    settingType: boolean = false;
    async getRouter() {
        if (this.reportRouter.length && this.bussinerRouter.length) return;
        const { data: routers } = await getRouters();
        Tools.setValueAndName(routers);
        // 把路由信息分为 报表路由和其他业务路由
        const reportRouter = routers.filter((item) => {
            const reportParentId = routers.find((router) => router.type === 4).parentId;
            return item.type === 4 || reportParentId === item.id;
        });
        const bussinerRouter = routers.filter((item) => item.type !== 4);
        this.reportRouter = nest(reportRouter, 0, 'parentId', false);
        this.bussinerRouter = nest(bussinerRouter, 0, 'parentId', false);
    }
    addModuleId(item) {
        this.addKey = item.value;
        if (['relationModuleList', 'relationReportList'].includes(item.value)) {
            this.getRouter();
            this.addModuleAndReport.isShowDialog = true;
        } else {
            this.linkModuleDialogObj.isShowDialog = true;
        }
    }
    moduleAndReportConfim() {
        const nodes = (this.$refs.baseTree as baseTree).getCheckedNodes();
        const chooseNodes = nodes.filter((item) => !item.children);
        this.deepModuleList.forEach((item) => {
            if (item.value === this.addKey) {
                item.list = [...item.list, ...chooseNodes];
            }
        });
    }
    deleteItem(item, list) {
        list.splice(item.$index, 1);
    }
    async linkModuleIdConfirm() {
        await (this.$refs.formlist as any).saveTable();

        this.deepModuleList.forEach((item) => {
            if (item.value === this.addKey) {
                item.list = [...item.list, this.linkFormData];
            }
        });
        this.linkModuleDialogObj.isShowDialog = false;
    }
    async confirm() {
        const postObj: Dictionary<any> = {
            settingType: Number(this.settingType)
        };
        this.deepModuleList.forEach((item) => {
            postObj[item.value] = item.list.map((config, index) => {
                return {
                    title: config.label,
                    content: config.moduleId,
                    orderNumber: config.orderNumber || index + 1,
                    type: item.value === 'relationModuleList' ? 1 : item.value === 'relationReportList' ? 2 : config.type
                };
            });
        });
        const res = await this._post({
            url: commonApi.settingRelationModuleId,
            data: {
                data: postObj
            }
        });
        if (res.code === 0) {
            this.$emit('settingSuccess');
        }
    }
    cancel() {
        this.$set(this.editViewsDialog, 'isShowDialog', false);
    }
    reset() {
        this.$emit('reset');
    }
}
</script>
<style lang="scss"></style>
<style lang="scss" scoped>
@import 'src/styles/variables.scss';
.edit-views {
    &-setting {
        text-align: right;
    }
    &-btn {
        text-align: right;
    }
}
.add-box {
    color: $colorTextRegular;
    height: 28px;
    line-height: 28px;
    border: 1px solid #eee;
    border-top: none;
    &-text {
        width: 50px;
        display: inline-block;
        padding-left: 10px;
        border-right: 1px solid #eee;
    }
    .inline-block {
        display: inline-block;
        width: 200px;
        padding-left: 10px;
        color: $basic;
        &:hover {
            cursor: pointer;
        }
    }
}
</style>
